#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <vector>
using namespace std;

typedef void (*ptr)();
vector<ptr> v;

void Worker()
{
    int cnt = 5;
    while (cnt)
    {
        printf("我是一个子进程:  %d, 我的pid是: %d \n", cnt--, getpid());
        sleep(1);
    }
}

void Test1()
{
    
    pid_t pid = fork();
    if (pid == 0)
    {
        //子进程
        Worker();
        exit(11);
    }
    else 
    {
        int state = 0;
        waitpid(pid, &state, 0);

        if (WIFEXITED(state))
        {
            printf("子进程退出码为: %d, 退出信号为: %d\n", WEXITSTATUS(state), state & 0x7F);    
        }
        else 
        {
            printf("子进程运行错误 \n");
        }
    
    }
}


void Work1()
{
    printf("这是一个临时工作1 \n");
}

void Work2()
{    
    printf("这是一个临时工作2 \n");
}

void Init()
{
    v.push_back(Work1);
    v.push_back(Work2);
}

void Test2()
{
    pid_t pid = fork();
    if (pid == 0)
    {
        Worker();
    }
    else 
    {
        int state = 0;
        Init();

        while (1)
        {
            int result = waitpid(pid, &state, WNOHANG);
            //waitpid返回值>0, 成功调用，子进程结束
            if (result == 0)
            {
                printf("子进程还没结束，父进程先做一下其他的事\n");
               
                size_t i = 0;
                for (i = 0; i < v.size(); i++)
                {
                    v[i]();
                }
            }
            else if (result > 0)
            {
                printf("子进程调用结束\n");
                break;
            }
            else 
            {
                printf("子进程调用失败\n");
                break;
            }
            sleep(1); 
        }
    }
}

int main()
{
    Test2();

    return 0;
}
